package knowse.app.presentation;

import java.io.IOException;
import java.util.ArrayList;

import knowse.app.FetchData;
import knowse.app.ProjectDataObject;
import knowse.app.R;
import knowse.app.TestDataObject;

import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TestListActivity extends ListActivity{

	ArrayList<String> projectEntries;
	ProjectDataObject po;
	
	private final String PROJFILE = "http://cse-212240.cse.chalmers.se/feldt/courses/agile2012/data/knowse/knowse_ruby_tests.csv";
	
	//oncreate
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.testlistactivity);
		
		projectEntries = new ArrayList<String>();
		populateProjectEntries();
		
		ArrayAdapter<String> adapter = 
				new ArrayAdapter<String>(this,
										 android.R.layout.simple_list_item_1,
										 projectEntries);
		setListAdapter(adapter);
		
	}
	
	private void populateProjectEntries(){
		//fetch the test file
		FetchData fd = new FetchData();
		projectEntries = new ArrayList<String>();
		try {
			po = new ProjectDataObject((String)fd.fetchCSV(PROJFILE));
			projectEntries.addAll(po.testEntryNames());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id){
		String item = (String) getListAdapter().getItem(position);
		System.out.println(item);
		
		try{
		    FetchData fetchdata=new FetchData();
		   
		    //Test fetching to JSONObject
		    JSONObject object=fetchdata.fetchJSON2Object("http://cse-212240.cse.chalmers.se/feldt/courses/agile2012/data/knowse/knowse_ruby_tests_problems_20120315_004757394.json");
		    //Create new TestDataObject and parsing JSONObject
		    TestDataObject testDataObject= new TestDataObject(object);
		    String timeStamp="20120315_004757394";
		    //throw an intent with testDataObject
		   
		    Intent intent=new Intent();
		    intent.setClass(TestListActivity.this, TestCaseActivity.class);
		    Bundle bundle=new Bundle();
		        bundle.putString("TimeStamp", timeStamp);
		        bundle.putParcelable("jsonFile", testDataObject);
		        intent.putExtras(bundle);
		        TestListActivity.this.startActivity(intent);
		   
		   
		    }catch(Exception e ){
		    System.out.println(e.getMessage());
		    }		
	}
	

}
